import os
import pandas as pd
from typing import List, Tuple, Dict
from src.core.models import Order, Trade
from src.storage.storage_interface import StorageInterface

class CSVStorage(StorageInterface):
    """CSV文件存储实现"""
    
    def __init__(self, orders_file: str, trades_file: str):
        self.orders_file = orders_file
        self.trades_file = trades_file
    
    def save_orders(self, orders: List[Order]) -> None:
        """保存订单到CSV文件"""
        if not orders:
            return
            
        df = pd.DataFrame([order.__dict__ for order in orders])
        
        if not os.path.exists(self.orders_file) or os.path.getsize(self.orders_file) == 0:
            df.to_csv(self.orders_file, index=False)
        else:
            df.to_csv(self.orders_file, mode='a', header=False, index=False)
    
    def save_trades(self, trades: List[Trade]) -> None:
        """保存交易到CSV文件"""
        if not trades:
            return
            
        df = pd.DataFrame([trade.__dict__ for trade in trades])
        
        if not os.path.exists(self.trades_file) or os.path.getsize(self.trades_file) == 0:
            df.to_csv(self.trades_file, index=False)
        else:
            df.to_csv(self.trades_file, mode='a', header=False, index=False)
    
    def get_orders(self) -> List[Order]:
        """从CSV文件读取订单"""
        if not os.path.exists(self.orders_file):
            return []
            
        df = pd.read_csv(self.orders_file)
        
        # 定义列名映射（从大写列名到小写属性名）
        column_mapping = {
            'Order ID': 'order_id',
            'Symbol': 'symbol',
            'Side': 'side',
            'Type': 'order_type',
            'Quantity': 'quantity',
            'Filled': 'filled',
            'Quantity Left': 'quantity_left',
            'Limit': 'limit_price',
            'Stop': 'stop_price',
            'Avg Fill Price': 'avg_fill_price',
            'Status': 'status',
            'Open Time': 'open_time',
            'Close Time': 'close_time',
            'Duration': 'duration',
            'Commission': 'commission',
            'Expiration': 'expiration',
            'Multiplier': 'multiplier'
        }
        
        # 重命名列
        df = df.rename(columns=column_mapping)
        
        return [Order(**row) for _, row in df.iterrows()]
    
    def get_trades(self) -> List[Trade]:
        """从CSV文件读取交易"""
        if not os.path.exists(self.trades_file):
            return []
            
        df = pd.read_csv(self.trades_file)
        return [Trade(**row) for _, row in df.iterrows()]
    
    def is_order_duplicate(self, order: Order) -> bool:
        """检查订单是否重复"""
        existing_orders = self.get_orders()
        if not existing_orders:
            return False
            
        for existing_order in existing_orders:
            if (str(existing_order.order_id).lower() == str(order.order_id).lower() and
                str(existing_order.symbol).lower() == str(order.symbol).lower() and
                str(existing_order.side).lower() == str(order.side).lower() and
                str(existing_order.order_type).lower() == str(order.order_type).lower() and
                str(existing_order.status).lower() == str(order.status).lower() and
                str(existing_order.filled).lower() == str(order.filled).lower() and
                str(existing_order.avg_fill_price).lower() == str(order.avg_fill_price).lower()):
                return True
        return False
    
    def is_trade_duplicate(self, trade: Trade) -> bool:
        """检查交易是否重复"""
        existing_trades = self.get_trades()
        if not existing_trades:
            return False
            
        for existing_trade in existing_trades:
            if (str(existing_trade.open_datetime).lower() == str(trade.open_datetime).lower() and
                str(existing_trade.close_datetime).lower() == str(trade.close_datetime).lower() and
                str(existing_trade.symbol).lower() == str(trade.symbol).lower() and
                str(existing_trade.open_price).lower() == str(trade.open_price).lower() and
                str(existing_trade.close_price).lower() == str(trade.close_price).lower()):
                return True
        return False 